import { Context } from "koa";
import { getCurrentTime } from "../utils";
import DbUtil from "../utils/db";
import { checkCollection } from "./util";

class UserCtl {
  static async getCollection(ctx: Context) {
    const { query } = ctx;
    return await checkCollection(query, ctx);
  }
  static async list(ctx: Context) {
    const collection = await UserCtl.getCollection(ctx);
    if (collection !== "") {
      const res = await DbUtil.query(collection, {
        where: ctx.query,
      });
      ctx.body = res;
    }
  }
  static async save(ctx: Context) {
    const { request } = ctx;
    const { body } = request;
    const collection = await UserCtl.getCollection(ctx);
    if (collection !== "") {
      body.createTime = getCurrentTime("yyyy-mm-dd HH:MM:SS", new Date());
      const res = await DbUtil.insert(collection, body);
      ctx.body = res;
    }
  }
  static async update(ctx: Context) {
    const { request } = ctx;
    const { body } = request;
    const collection = await UserCtl.getCollection(ctx);
    if (collection !== "") {
      const res = await DbUtil.update(collection, body._id, body);
      ctx.body = res;
    }
  }
  static async delete(ctx: Context) {
    const { request } = ctx;
    const { body } = request;
    const collection = await UserCtl.getCollection(ctx);
    if (collection !== "") {
      const res = await DbUtil.delete(collection, body.id);
      ctx.body = res;
    }
  }
}

export default UserCtl;
